package eerbaar.shared.persist.internal.lib;

import java.util.ArrayList;
import java.util.List;

import eerbaar.level.IHint;
import eerbaar.level.IHints;
import eerbaar.level.LevelFactory;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.exceptions.GameRuntimeException;
import eerbaar.shared.persist.IPersistService;
import eerbaar.shared.persist.IPersister;
import eerbaar.shared.persist.ISaver;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;

public class HintsPersister implements IPersister<IHints> {

    public static final String NAME = "hints";

    private IHints target;

    public HintsPersister() {
        //
    }

    public HintsPersister(IHints wrapper) {
        this.target = wrapper;
    }

    public HintsPersister(INode node) throws GameRuntimeException {
        load(node);
    }

    @Override
    public Class<IHints> getRegistertedInterface() {
        return IHints.class;
    }

    @Override
    public ISaver<?>[] getSavableChildren() {

        List<HintPersister> result = new ArrayList<HintPersister>();

        IHint[] hints = this.target.getHints();
        for (IHint e : hints) {
            HintPersister p = new HintPersister(e);
            result.add(p);
        }

        return result.toArray(new ISaver<?>[] {});
    }

    @Override
    public String getSavableName() {

        return NAME;
    }

    @Override
    public IHints getTarget() {
        return this.target;
    }

    @Override
    public boolean isAssignableFrom(ISaver<?> savable) {
        return false;
    }

    @Override
    public IHints load(INode node) {
        assert (node != null);

        IHints result = LevelFactory.createHints();

        IPersistService service = ServiceFactory
                .getService(IPersistService.class);

        List<INode> list = NodeCmdFactory
                .findChildren(node, HintPersister.NAME);
        for (INode n : list) {
            try {
                IHint hint = service.load(IHint.class, n);
                result.addHint(hint);
            } catch (GameException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    public void saveAttributes(INode node) {
        //
    }

    @Override
    public void setTarget(IHints obj) {
        this.target = obj;
    }

}
